define(function(require,exports,module){
	/**--tmpl-require--**/
	
	//加载依赖
	require("ajaxproxy");
	require("areaselect");


	var common = require("common");

	//初始化AjaxProxy插件
	$('.ajaxproxy').AjaxProxy({
		dataType : "json",
		method : "post",
		formId : "content-add-form",
		formCheckHandler : function(form_id) {
			return common.formCheckHandler(form_id, true);
		},
		callbackDelay : __global.jdialog.timer,
		timeInterval : __global.jdialog.timer,
		callBefore:function(){
			var $error = $(".error");
			if($error.length>0){
				$error.each(function(i,e){
					if($(e).hasClass("num")){
						check.num($(e));
					}else{
						check.price($(e));
					}
				});
				return false;
			} else {
				return true;
			}
		},
		callBack : function (data) {   /* 执行ajax之后的回调函数 */
			common.ajaxCallback(data);
		}
	});

	exports.init = function(config){

		/**
		 * 地区选择
		 */
		$(".area-wrap").JAreaSelect();
		/**
		 * 搜索商品
		 */
		$("#product_search").on("click", function () {
			product_no = $("input[name='product_no']").val();
			member_id = $("input[name='member_id']").val();
			if(product_no == ''){
				layer.tips('请输入产品货号搜索',$("input[name='product_no']"));
				return ;
			}
			searchProduct(config.searchProductrUrl,product_no,member_id);
		});

		/**
		 * 搜索会员
		 */
		$("#member_search").on("click", function () {
			phone_no = $("input[name='member_phone']").val();
			searchMember(config.searchMemberUrl,phone_no);
		});

		/**
		 * 新增收货地址
		 */
		$("#add_address").on("click",function () {
			var __JF = new JForm();
			province = $("select[name='province']").val();
			city = $("select[name='city']").val();
			dist = $("select[name='dist']").val();
			address = $("input[name='address[address]']").val();
			detail = $("input[name='detail").val();
			consignee = $("input[name='address[consignee]']").val();
			zip_code = $("input[name='address[zip_code]']").val();
			contact_mobile = $("input[name='address[contact_mobile]']").val();
			telephone = $("input[name='address[telephone]']").val();
			member_id = $("input[name='member_id']").val();
			if(address == ''){
				layer.tips("请填写地址信息",$("input[name='address[address]']"));
				return false;
			}
			if(consignee == ''){
				layer.tips("请填写收货人姓名",$("input[name='address[consignee]']"));
				return false;
			}
			if(contact_mobile == ''){
				layer.tips("请填写收货人联系方式",$("input[name='address[contact_mobile]']"));
				return false;
			}
			if(member_id == ''){
				layer.tips("请输入正确的会员手机号搜索",$("input[name='member_id']"));
				return false;
			}
			__JF.regExpCheck($("input[name='address[contact_mobile]']")[0]);
			arr = {province:province,city:city,dist:dist,address:address,detail:detail,consignee:consignee,zip_code:zip_code,contact_mobile:contact_mobile,telephone:telephone,member_id:member_id};
			$.post(config.addAddressUrl, arr, function (data) {
				console.info(data);
				if(data.code == '000'){
					data = data.data;
					//成功后输出到收货地址列表
					address_info = 	'<div><input type="radio" checked="checked" name="address_id" id="address_id_' + data.id + '" value="' + data.id + '"><label for="address_id_' + data.id + '">&nbsp;' + data.consignee + '&nbsp;' + data.contact_mobile + '&nbsp;&nbsp;' + data.detail_address + '&nbsp;&nbsp;' + data.zip_code + '</label></div>';
					console.log(member_id);
					$("#address_list").append(address_info);
					$("#add_address").addClass("disabled");
					setInterval(removeDisabled,10000);
				}else if(data.code == '001') {//添加失败

				}
			}, 'json');
		});

		/**
		 * 商品库
		 */
		$('#select_product').on('click', function(){
			var member_id = $("input[name='member_id']").val();
			if(member_id == ''){
				layer.tips("请您先输入手机号码搜索会员再操作下面的步骤",$("input[name='member_phone']"));
				return false;
			}
			layer.open({
				type: 2,
				title: '商品库',
				shadeClose: false,
				shade: 0.8,
				btn:["确定","取消"],
				area: ['90%', '90%'],
				content: config.searchProductListrUrl + "?member_id=" + member_id,
				yes:function (index,layero) {

					var body = layer.getChildFrame('body');
					body.find("#J_ListTable .icheck-td").each(function(e,i){
						//console.log(e);
						if($(this).children("div").children(".icheck").is(":checked")){
							var val = $(this).children(".product_info").val();
							setProductInList($(".product_list"),$.parseJSON(val));
							layer.close(index);
							$("input[name='have_products']").val(1);
						}
					});

				}
			});
		});

		//交收方式信息切换
		$("#shipping_way").on("change",function(){
			var val = $(this).val();
			if(val==1){
				$(".shipping_way_get").removeClass("hidden").find("input").prop("disabled",false);
				$(".shipping_way_send").addClass("hidden").find("input").prop("disabled",true);
			}else {
				$(".shipping_way_send").removeClass("hidden").find("input").prop("disabled",false);
				$(".shipping_way_get").addClass("hidden").find("input").prop("disabled",true);
			}
		}).change();
	};

	function removeDisabled() {
		$("#add_address").removeClass("disabled")
	}

	/**
	 * 新增收货地址
	 */
	$("#new_add_address").on("click",function () {
		$("#address_form").attr("style","display:");
	});
	$("#close_add_address").on("click",function () {
		$("#address_form").attr("style","display:none");
	});

//计算商品总值
	function cal_price() {
		var total_price = 0;
		$(".product_list").find(".now_price").each(function(e,i){
			var val;
			if(this.value==""){
				val = $(this).parent().siblings(".origin_price").html();
			}else {
				val = this.value;
			}
			total_price=total_price+parseFloat(val);
		});
		$("#total_price").html(total_price);
	}
//商品规则校验
	var check = {
		price:function(that){
			var val = that.val();
			var $obj = that.parents("tr");
			var reg= /^([1-9]\d{0,4}|[0])(\.\d{1,2})?$/;
			var result = reg.test(val);
			if(val==0){
				that.addClass("error");
				layer.tips("价格必须大于0 ",that);
				return false;
			}else if(result) {
				that.removeClass("error");
				var discount = val - $obj.find(".origin_price").html();
				discount = discount.toFixed(2);
				$obj.find(".discount").html(discount);
				cal_price();
			}else {
				that.addClass("error");
				layer.tips("请输入正确的价格",that);
				return false;
			}
		},num:function(that){
			var val = that.val();
			var $obj = that.parents("tr");
			var sales_price = $obj.find(".sales_price").val();
			var min_num = that.attr('min');
			var max_num = that.attr('max');
			var price = val*sales_price;
			price = price.toFixed(2);
			var reg= /^([1-9]\d*|[0])(\.\d{1,3})?$/;
			var result = reg.test(val);
			if(!result) {
				that.addClass("error");
				layer.tips("请输入正确的数量",that);
				return false;
			}else if(val*1>max_num*1){
				that.val(max_num);
				price=max_num*sales_price;
				layer.tips("数量不能大于现有库存",that);
			}else if(val*1<min_num*1){
				that.val(min_num);
				price=min_num*sales_price;
				layer.tips("数量不能小于最小交易量",that);
			}
			that.removeClass("error");
			$obj.find(".origin_price").html(price);
			$obj.find(".now_price").val(price);
			$obj.find(".discount").html(0);
			cal_price();
		}
	}
	/**
	 * 会员搜索API
	 */

	function searchMember(url,phone_no) {
		var url = url+"?phone_no="+phone_no;
		$.getJSON(url, function (data) {
			var listObj = $("#address_list");
			//console.info(data);
			if(data.code == '000'){
				var res = data.data;
				if(res.member_id){
					$("input[name='member_id']").val(res.member_id);
					listObj.html("");
				}else{
					setAddressInList(listObj,res);
				}
				$("#new_add_address").removeClass("disabled");
			}else if(data.code == '001') {//没有此用户
				//console.log(data.message);
				$("#new_add_address").addClass("disabled");
				$("input[name='member_id']").val('');
				listObj.html("");
				$("#address_form").attr("style","display:none");
				layer.tips("没有此用户",$("input[name='member_phone']"));
			}
		});
	}

	/**
	 * 商品搜索API
	 */

	function searchProduct(url,product_no,member_id) {
		if(member_id == ''){
			layer.tips("请您先输入手机号码搜索会员再操作下面的步骤",$("input[name='member_phone']"));
			return false;
		}
		var url = url+"?product_no=" + product_no + "&member_id=" + member_id;
		$.getJSON(url, function (data) {
			var listObj = $(".product_list");
			//console.info(data);
			if(data.code == '000'){
				$(data.data).each(function (index, el) {
					setProductInList(listObj,el);
				});
				$("input[name='have_products']").val(1);
			}else if(data.code == '001') {//没有此产品
				console.log(data.message);
			}
		});
	}

	function setAddressInList(listObj, data) {
		listObj.html(function () {
			var s = "";
			$(data).each(function (index, el) {
				//console.log(el);
				if(index==0){
					$("input[name='member_id']").val(el.member_id);
				}
				checked = el.default_type==1?'checked="checked"':'';//默认选中
				s = s + '<div><input type="radio" '+ checked +' name="address_id" id="address_id_' + el.id + '" value="' + el.id + '"><label for="address_id_' + el.id + '">&nbsp;' + el.consignee + '&nbsp;' + el.contact_mobile + '&nbsp;&nbsp;' + el.detail_address + '&nbsp;&nbsp;' + el.zip_code + '</label></div>';
			});
			return s;
		});
	}

	function setProductInList(listObj, data) {
		if(document.getElementById("product_id_" + data.id)){

		}else{
			listObj.append(function () {
				var s = "";
				var quantity = data.quantity*1-data.freeze_quantity*1;
				quantity = quantity.toFixed(3);
				if(quantity<=0){
					return '';
				}
				var price = data.min_volume*data.sales_price;
				price = price.toFixed(2);
				s = s + '<tr id="product_id_' + data.id + '">';
				s = s + '<input type="hidden" name="product[product_id][]" value="' + data.id + '">';
				s = s + '<input type="hidden" name="product[product_price][]" class="sales_price" value="' + data.sales_price + '">';
				s = s + '<td>' + data.type_name + '/' + data.product_name + '/' + data.factory_name + '/' + data.brand_name + '<br/>货品规格(KG/袋)：' + data.pkg_size + '</td>';
				s = s + '<td>' + data.product_no + '</td>';
				s = s + '<td style="text-decoration: line-through">' + data.orgin_sales_price + '</td>';
				s = s + '<td>' + data.sales_price + '</td>';
				s = s + '<td>' + quantity + '</td>';
				s = s + '<td>' + data.min_volume + '</td>';
				s = s + '<td class="col-sm-1"><input type="text" class="form-control num" name="product[product_quantity][]" placeholder="数量" cname="数量" value="' + data.min_volume + '" min="' + data.min_volume + '" max="' + quantity + '"></td>';
				s = s + '<td class="origin_price">' + price + '</td>';
				s = s + '<td class="col-sm-1"><input type="text" class="form-control now_price" name="product[product_actual_price][]" placeholder="金额" cname="金额" value="' + price + '"></td>';
				s = s + '<td class="col-sm-2 discount"></td>';
				s = s + '<td><a href="javascript:void(0);" class="btn btn-danger btn-xs product_del"><i class="glyphicon glyphicon-trash"></i> 删除</a></td>';
				s = s + '</tr>';
				return s;
			});
			cal_price();
		}
	}


		/**
		 * 移除商品
		 */
		$(".product_list").on("click",".product_del",function () {
			$(this).parents("tr").remove();
			cal_price();
			if($(".product_list").has('tr').get(0)){
				//console.log('还有产品');
			}else{
				//console.log('没有产品');
				$("input[name='have_products']").val("");
			};
		});



	$(".product_list").on("blur",".num",function(){
		var that = $(this);
		check.num(that);
	});

	$(".product_list").on("keyup",".now_price",function(){
		var that = $(this);
		check.price(that);

	});

});
